<template>
  <div class="announcement-container">
    <el-card>
      <div slot="header" class="header">
        <span>公告信息</span>
        <el-button type="primary" @click="handleAdd" v-if="isAdmin">新增公告</el-button>
      </div>

      <el-timeline>
        <el-timeline-item
          v-for="item in announcementList"
          :key="item.id"
          :timestamp="item.createTime"
          :type="item.type === '重要' ? 'danger' : item.type === '普通' ? 'primary' : 'info'"
          placement="top"
        >
          <el-card class="announcement-card">
            <div class="announcement-header">
              <h3 class="announcement-title">{{ item.title }}</h3>
              <el-tag :type="item.type === '重要' ? 'danger' : item.type === '普通' ? 'primary' : 'info'">
                {{ item.type }}
              </el-tag>
            </div>
            <div class="announcement-content">
              <p>{{ item.content }}</p>
            </div>
            <div class="announcement-footer" v-if="isAdmin">
              <el-button type="text" @click="handleEdit(item)">编辑</el-button>
              <el-button type="text" class="delete-btn" @click="handleDelete(item)">删除</el-button>
            </div>
          </el-card>
        </el-timeline-item>
      </el-timeline>

      <div class="pagination" v-if="total > 0">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page"
          :page-sizes="[5, 10, 20, 50]"
          :page-size="size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px">
      <el-form :model="announcementForm" :rules="rules" ref="announcementForm" label-width="100px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="announcementForm.title"></el-input>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="announcementForm.type" placeholder="请选择公告类型">
            <el-option label="重要" value="重要"></el-option>
            <el-option label="普通" value="普通"></el-option>
            <el-option label="通知" value="通知"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input type="textarea" v-model="announcementForm.content" :rows="6"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'

export default {
  name: 'Announcement',
  data() {
    return {
      announcementList: [],
      page: 1,
      size: 10,
      total: 0,
      dialogVisible: false,
      dialogTitle: '新增公告',
      announcementForm: {
        title: '',
        type: '普通',
        content: ''
      },
      rules: {
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择公告类型', trigger: 'change' }
        ],
        content: [
          { required: true, message: '请输入内容', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    ...mapGetters(['isAdmin'])
  },
  created() {
    this.fetchAnnouncementList()
  },
  methods: {
    async fetchAnnouncementList() {
      try {
        const response = await this.$http.get('/notice/list', {
          params: {
            pageNo: this.page,
            pageSize: this.size
          }
        })
        if (response.data.code === 20000) {
          const data = response.data.data
          this.announcementList = (data.rows || []).map(item => ({
            id: item.id,
            title: item.theme,
            type: item.type || '普通',
            content: item.content,
            createTime: item.issueTime
          }))
          this.total = data.total
        } else {
          throw new Error(response.data.message || '获取公告列表失败')
        }
      } catch (error) {
        console.error('获取公告列表失败:', error)
        this.$message.error(error.message || '获取公告列表失败')
      }
    },
    handleSizeChange(val) {
      this.size = val
      this.fetchAnnouncementList()
    },
    handleCurrentChange(val) {
      this.page = val
      this.fetchAnnouncementList()
    },
    handleAdd() {
      this.dialogTitle = '新增公告'
      this.announcementForm = {
        title: '',
        type: '普通',
        content: ''
      }
      this.dialogVisible = true
    },
    handleEdit(item) {
      this.dialogTitle = '编辑公告'
      this.announcementForm = { ...item }
      this.dialogVisible = true
    },
    async handleDelete(item) {
      try {
        await this.$confirm('确认删除该公告吗？', '提示', {
          type: 'warning'
        })
        const response = await this.$http.delete(`/notice/${item.id}`)
        if (response.data.code === 20000) {
          this.$message.success('删除成功')
          this.fetchAnnouncementList()
        } else {
          throw new Error(response.data.message || '删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除失败:', error)
          this.$message.error(error.message || '删除失败')
        }
      }
    },
    submitForm() {
      this.$refs.announcementForm.validate(async valid => {
        if (valid) {
          try {
            const noticeData = {
              theme: this.announcementForm.title,
              type: this.announcementForm.type,
              content: this.announcementForm.content
            }
            let response
            if (this.announcementForm.id) {
              noticeData.id = this.announcementForm.id
              response = await this.$http.put('/notice', noticeData)
            } else {
              response = await this.$http.post('/notice', noticeData)
            }
            
            if (response.data.code === 20000) {
              this.$message.success('保存成功')
              this.dialogVisible = false
              this.fetchAnnouncementList()
            } else {
              throw new Error(response.data.message || '保存失败')
            }
          } catch (error) {
            console.error('保存失败:', error)
            this.$message.error(error.message || '保存失败')
          }
        }
      })
    }
  }
}
</script>

<style scoped>
.announcement-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.announcement-card {
  margin-bottom: 10px;
}

.announcement-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.announcement-title {
  margin: 0;
  font-size: 16px;
  font-weight: bold;
}

.announcement-content {
  color: #606266;
  line-height: 1.6;
}

.announcement-footer {
  margin-top: 10px;
  display: flex;
  justify-content: flex-end;
}

.delete-btn {
  color: #F56C6C;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style> 